<?php

/**
 * @package    [PACKAGE_NAME]
 *
 * @author     [AUTHOR] <[AUTHOR_EMAIL]>
 * @copyright  [COPYRIGHT]
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       [AUTHOR_URL]
 */


use Joomla\CMS\MVC\Controller\BaseController;

use EasyWeChat\Factory as WechatFactory;

use Joomla\CMS\Log\Log;

// require __DIR__ . '/wxBizDataCrypt.php';

defined('_JEXEC') or die;

/**
 * WxMinipro controller.
 *
 * @package  [PACKAGE_NAME]
 * @since    1.0.0
 */
class WxMiniproControllerWxUser extends BaseController
{

    public $config = [
        'app_id' => 'wx564bd9f2ea5cf881',
        'secret' => '7cf335f85fff2ffa74a14de0fe8ded2f',

        // 下面为可选项
        // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
        'response_type' => 'array',

        'log' => [
            'level' => 'debug',
            'file' => __DIR__ . '/wechat.log',
        ],
    ];

    public function display($cachable = false, $urlparams = array())
    {
        echo "hell wxuer";
        return;
    }

    public function getskey()
    {
        $res = [
            'result' =>   -1,
            'errmsg' => '未知错误',
        ];

        $jinput = $this->input;
        $code = $jinput->get('code');
        if (!$code) {
            $res['errmsg'] = '没有code';
            echo json_encode($res);
            jexit();
        }

        $app = WechatFactory::miniProgram($this->config);

        $response = $app->auth->session($code);
        if (isset($response['openid'])) {
            JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_wxminipro/tables');
            $usertbl = JTable::getInstance('WxUser', 'Table', array());

            $id = $usertbl->getIdby($response['openid']);

            if ($id && $usertbl->load($id)) {
                $res['skey'] = $usertbl->skey;
                if ($usertbl->nickName && $usertbl->avatarUrl) {
                    $userinfo['nickName'] = $usertbl->nickName;
                    $userinfo['avatarUrl'] = $usertbl->avatarUrl;
                    $res['userInfo'] = $userinfo;
                }
            } else {
                $usertbl->openid = $response['openid'];
                $usertbl->sessionkey = $response['session_key'];
                $usertbl->skey = sha1($response['openid'] . 'zhuameng');
                $res['skey'] = $usertbl->skey;
                $usertbl->create_time = date("Y-m-d H:i:s");
                $usertbl->store();
            }

            $res['errmsg'] = '成功';
            $res['result'] = 0;
        } else {
            $res['errmsg'] = '获取openID失败';
        }
        echo json_encode($res);
        jexit();
    }

    public function getuserinfo()
    {
        $res = [
            'result' =>   -1,
            'errmsg' => '未知错误',
        ];

        $jinput = $this->input;;
        $skey = $jinput->get('skey');
        if (!$skey) {
            $res['errmsg'] = '缺少 skey';
            echo json_encode($res);
            jexit();
        }
        JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_wxminipro/tables');
        $usertbl = JTable::getInstance('WxUser', 'Table', array());
        $id = $usertbl->getIdby($skey, 'skey');


        $rawdata = $jinput->get('rawData', null, 'RAW');
        if ($rawdata) {
            $userinfo = json_decode($rawdata);

            //将userinfo存入数据库
            $usertbl->id = $id;
            $usertbl->nickName = $userinfo->nickName;
            $usertbl->gender = $userinfo->gender;
            $usertbl->avatarUrl = $userinfo->avatarUrl;
            $usertbl->update_time = date("Y-m-d H:i:s");
            $resdb = $usertbl->store();
            $res['errmsg'] = '成功';
            $res['result'] = 0;
            $res['userInfo'] = $userinfo;
        }

        echo json_encode($res);
        jexit();
    }


    public function testjiemi()
    {
        $rawdata = '{"nickName":"JiaMing","gender":0,"language":"zh_CN","city":"","province":"","country":"Albania","avatarUrl":"https://wx.qlogo.cn/mmopen/vi_32/OtyczrBlZhTjLUXjwib3bWDa6ibt1yphoTeib7icckWkJEk3W68x8vZbbdfwGDcKL4GmeiafIqXfj3nAgHwgxSfpgqw/132"}';
        var_dump(json_decode($rawdata));
        // $appid = 'wx9ca2891f028bc46c';
        // $sessionKey = 'mhEBcdtYBPwEgZD50OlfVw==';

        // $encryptedData = "P9p2F1RU7ZBLXKJamn+qrUHdv7c/bHmwbtqdgFZ141kpFuvdelp10JH/Hkc9ssKGNLXZIqGwIfJuThFjk9uSkecLmjA4CZZ8OPfbTlToeK0wjOdP8nINPbjDpd5aGh3mzxXPHI6Z9ExVgArVcqSk2LuHlOvncUX8FnqMdSV4LxU6n/+pIYaW4ZrwFvn3VKIE7uKpfpX8RkX5GAIAwSqMdDZy47Hdh47SP4WiXHJfBAAsMl5PKxw77cFjmYlG0HmoplhwZYki6V83RabYxeNcZPevfBnBVYq8goPxrfUZ15q49uWFgz5Sd2jw/mNHdibRdPSuOvmxX7nDQjtK9PoSsoZjB/LTQdcEpyKj5Y5pQ4OKDgcw4AEUSR4nYZFoJkOMvmx75x1W2u94XH3YXTJmzE8xooV/5j5k+wC/28hhynOk6XqVe4rOFGPZEfmc0PQfUaGA73mwXMLQNJoenBAhmQ==";

        // $iv = 'JRLwLgn3s1z49OS+w7DmHQ==';

        // $pc = new WXBizDataCrypt($appid, $sessionKey);
        // $errCode = $pc->decryptData($encryptedData, $iv, $data);

        // if ($errCode == 0) {
        //     print($data . "\n");
        // } else {
        //     print($errCode . "\n");
        // }
        // jexit();
    }
}
